import { getAllWorkers, queryInAndOutByPeopleAndDay } from '@/services/bimServices';
import moment from 'moment';

export function processPplData(allWorkers = [], todayWorkers = []) {
  const workerByType = allWorkers.reduce((r, { userType }) => {
    if (!r[userType]) {
      r[userType] = 0;
    }
    r[userType] += 1;
    return r;
  }, {});

  const curWorkingWorkerByType = todayWorkers.reduce((r, { userType, outTm }) => {
    if (!r[userType]) {
      r[userType] = 0;
    }
    if (!outTm) {
      r[userType] += 1;
    }
    return r;
  }, {});

  const fullData = Object.keys(workerByType)
    .reduce((r, key) => {
      if (key !== '其他') {
        r.push([key, workerByType[key] || 0, curWorkingWorkerByType[key] || 0]);
      }
      return r;
    }, [])
    .sort((a, b) => {
      return b[1] - a[1];
    });

  fullData.push(['其他', workerByType['其他'] || 0, curWorkingWorkerByType['其他'] || 0]);
  const chartData = fullData.slice(0, 6).reduce(
    (r, e) => {
      const [name, full, online] = e;
      r[0].unshift(name);
      r[1].unshift(online);
      r[2].unshift(full - online);
      return r;
    },
    [[], [], []],
  );
  const restData = fullData.slice(7);
  console.log([fullData, chartData, restData]);
  return [fullData, chartData, restData];
}

// 读取mock
export function getPplData() {
  let params = new URL(document.location).searchParams;
  let projectId = params.get('i');
  return fetch('./config/人员管理.json')
    .then(r => r.json())
    .then(data => {
      projectId = projectId || Object.keys(data)[1];
      let _data = data[projectId];

      return [
        _data,
        _data.slice(0, 6).reduce(
          (r, e) => {
            const [name, full, online] = e;
            r[0].unshift(name);
            r[1].unshift(online);
            r[2].unshift(full - online);
            return r;
          },
          [[], [], []],
          _data.slice(7),
        ),
      ];
    });
}

// 真实系统api
// export function getPplData(itemId = 'DY7602103101106279') {
//   // 默认高浪路
//   return Promise.all([
//     getAllWorkers(itemId),
//     queryInAndOutByPeopleAndDay(itemId, moment().format('YYYY-MM-DD')),
//   ]).then(([allWorkers, todayWorker]) => {
//     try {
//       let data = processPplData(allWorkers.data.data, todayWorker.data.data);
//       console.log(data);
//       return data;
//     } catch (error) {
//       return [[], [], []];
//     }
//   });
// }
